package com.zjsru.oneDay202209;

import java.util.Arrays;

/**
 * @Author: likew
 * @Date: 2022/9/27
 *  判定是否互为字符重排
 * 输入: s1 = "abc", s2 = "bca"
 * 输出: true
 *
 */
public class CheckPermutation {
    /**
     * 统计过程中使用变量 tot 记录词频不同的字符个数。
     * */
    public boolean CheckPermutation(String s1, String s2) {
        int n = s1.length(), m = s2.length(), tot = 0;
        if (m != n) {
            return false;
        }
        int[] ans = new int[256];
        for (int i = 0; i < n; i++) {
            //该字符未出现过
            if (++ans[s1.charAt(i)] == 1) {
                tot++;
            }
            //该字符已经在出现过
            if (--ans[s2.charAt(i)] == 0) {
                tot--;
            }
        }
        return tot == 0;
    }
    
    /**
     * 排序
     * */
    public boolean CheckPermutation2(String s1, String s2) {
        if(s1.length() != s2.length()){
            return false;
        }
        char[] chars1 = s1.toCharArray();
        char[] chars2 = s2.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        return Arrays.equals(chars1,chars2);
    }
    
    /**
     * 哈希表
     * */
    public boolean CheckPermutation3(String s1, String s2) {
        if(s1.length() != s2.length()){
            return false;
        }
        int[] ans = new int[128];
        for (int i = 0; i < s1.length(); i++) {
            ans[s1.charAt(i)]++;
        }
        for (int i = 0; i < s2.length(); i++) {
            ans[s2.charAt(i)]--;
            if(ans[s2.charAt(i)] < 0){
                return false;
            }
        }
        return true;
    }
    
    /**
     * ASCII直接比较数字累计之和是否相等
     * */
    public boolean CheckPermutation4(String s1, String s2) {
        if(s1.length() != s2.length()){
            return false;
        }
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < s1.length(); i++) {
            sum1 += s1.charAt(i);
        }
        for (int i = 0; i < s2.length(); i++) {
            sum2 += s2.length();
        }
        return sum1 == sum2;
    }
    
    public static void main(String[] args) {
        CheckPermutation checkPermutation = new CheckPermutation();
        String s1 = "abc";
        String s2 = "bad";
        System.out.println(checkPermutation.CheckPermutation(s1, s2));
    }
}
